package medicalDocumentation.medicalRepository;

import entity.ClinicalPathway;
import entity.Disease;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
public class DiseaseRepositorySessionBean implements DiseaseRepositorySessionBeanRemote {
    
    public final String DISEASE_CODE_REQUIRED = "Disease code required";
    public final String DISEASE_CODE_DUPLICATE = "Duplicate disease code";
    @PersistenceContext
    private EntityManager entityManager;

    public DiseaseRepositorySessionBean() {
    }

    @Override
    public String addDisease(String code, String name, String clinicalPathwayId, String remark) {
        if (code == null) {
            return DISEASE_CODE_REQUIRED;
        }
        if (getDiseaseByCode(code).size() > 0) {
            return DISEASE_CODE_DUPLICATE;
        }
        Disease disease = new Disease();
        disease.setCode(code);
        disease.setName(name);
        disease.setRemark(remark);
        entityManager.persist(disease);
        entityManager.flush();
        return disease.getCode();
    }

    @Override
    public List<Disease> getDiseaseByCode(String code) {
        String strQuery = "SELECT d FROM Disease d WHERE d.code = :inCode";
        Query query = entityManager.createQuery(strQuery);
        query.setParameter("inCode", code);
        return query.getResultList();
    }

    @Override
    public List<Disease> getAllDiseases() {
        String strQuery = "SELECT d FROM Disease d";
        Query query = entityManager.createQuery(strQuery);
        return query.getResultList();
    }

    @Override
    public void deleteDisease(String code) {
        List diseases = getDiseaseByCode(code);
        if (diseases.get(0) != null) {
            entityManager.remove(diseases.get(0));
            entityManager.flush();
        }
    }

    @Override
    public void updateDisease(String code, String name, String remark, String clinicalPathway) {
        Disease disease = getDiseaseByCode(code).get(0);
        
        if (disease != null) {
            disease.setName(name);
            disease.setRemark(remark);
            entityManager.merge(disease);
            entityManager.flush();
        }
        
    }
}
